import json
import uuid
from random import randint

from django.core.cache import caches
from rest_framework.exceptions import ValidationError

from .sdk import SendSmsRequest
from .sdk.aliyunsdkcore.client import AcsClient

sms_code_cache = caches['sms_code']

"""
短信业务调用接口示例，版本号：v20170525

Created on 2017-06-12

"""

REGION = "cn-hangzhou"
# ACCESS_KEY_ID/ACCESS_KEY_SECRET 根据实际申请的账号信息进行替换
ACCESS_KEY_ID = "LTAIG91Ldsf6U8Rb"
ACCESS_KEY_SECRET = "SDCgfQoUSRDq7v0NFB1uBcA9pOtD32"

acs_client = AcsClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET, REGION)


def send_sms(phone_number):
    smsRequest = SendSmsRequest.SendSmsRequest()
    # 申请的短信模板编码,必填
    smsRequest.set_TemplateCode('SMS_84675003')

    # 短信模板变量参数
    code = generate_validate_code()
    smsRequest.set_TemplateParam('{"number": "%s"}' % code)

    business_id = uuid.uuid1()
    # 设置业务请求流水号，必填。
    smsRequest.set_OutId(business_id)

    # 短信签名
    smsRequest.set_SignName(u'华焱农贸')

    # 短信发送的号码列表，必填。
    smsRequest.set_PhoneNumbers(phone_number)

    # 调用短信发送接口，返回json
    smsResponse = acs_client.do_action_with_exception(smsRequest)

    response = json.loads(smsResponse.decode('utf-8'))
    if 'OK' == response['Code']:
        sms_code_cache.set(phone_number, code, 180)  # 记录手机号码和验证码，3分钟过期
    else:
        raise ValidationError(detail=response['Message'])


def generate_validate_code():
    number = randint(0, 999999)
    return "%06d" % number


def validate_sms_code(phone_number, sms_code):
    if sms_code:
        return sms_code == sms_code_cache.get(phone_number)
    return False
